import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Button,
  Input,
  Modal,
  message,
  Form,
  Select,
  Checkbox,
  Table,
  Pagination,
  Upload,
  Icon,
  Radio,
  Spin,
  TreeSelect,
  Switch,
  Card,
} from 'antd';
import download from '@/utils/download';
import axios from 'axios';
import styles from './index.less';
import qs from 'qs';
import addImg from '@/assets/knowledge/add.png';
import importImg from '@/assets/knowledge/import.png';
import exportImg from '@/assets/knowledge/export.png';
import delImg from '@/assets/knowledge/del.png';
import mergeImg from '@/assets/knowledge/merage.png';
import moveImg from '@/assets/knowledge/move.png';
import del1Img from '@/assets/knowledge/del1.png';
import editImg from '@/assets/knowledge/edit.png';
import moreImg from '@/assets/knowledge/more.png';
import onImg from '@/assets/knowledge/on.png';
import offImg from '@/assets/knowledge/off.png';
import searchImg from '@/assets/knowledge/search.png';

const Option = Select.Option;
const confirm = Modal.confirm;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const TreeNode = TreeSelect.TreeNode;
@connect(({ qaList, loading }) => ({
  qaList,
  loading: loading.effects['qaList/fetchListBySearch'],
}))

class QaList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      limit: 10,
      categoryId: "",
      visible: false,
      qaIdList: [],
      fileList: [],
      close: false,
      categoryName:'所有分类',
      loading:false,
      tableLoading: true,
      mergeVisible: false,
      key:'',
      qaLimit:6,
      qaPage:1,
      qaRes:[],
      qaTotal:0,
      qaLoading: true,
      res:[],
      total:0,
      mergeId:'',
      classVisible: false,
      classLoading: true,
      classTreeData: [],
      classId:'',
      qaKey:'',
      searchObj: { },
      nodePath:'',
      code:1,
      queryType:"question",
      sortType:props.slotType?props.slotType:'updateTime',
      disabled:"All",
      qaType:"All",
      selectedRowKeys:[],
      fileList: [],
      uploading: false,
      isNoAnswer:false,
      isShard:false
    };
    this.columns = [
      {
        key: 'stdQuestion',
        align: 'left',
        title: '标准问',
        dataIndex: 'stdQuestion',
        render:(text,row)=>{
         return <span style={{color:"grey",cursor:"pointer"}} onClick={() => this.editQa(row)}>{row.stdQuestion}</span>
        },
      },
      {
        key: 'questionCount',
        align: 'center',
        title: '相似问数量',
        dataIndex: 'questionCount',
        width: 150,
      },
      {
        key: 'qaType',
        align: 'center',
        title: '知识点类型',
        dataIndex: 'qaType',
        width: 150,
      },
      {
        title: '操作',
        align: 'center',
        render: (text, row) => {
          return <div>
                <div className={styles.tool}>
                  <img src={editImg} alt="编辑知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.editQa(row)} />
                  <img src={del1Img} alt="删除知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.delQaByQaId(row)} />
                  {
                    row.disabled?
                      <img src={offImg} style={{cursor:"pointer",width:30,marginTop:5}} alt="" onClick={()=>this.stopQaByQaId(row,false)} />
                      :
                      <img src={onImg} style={{cursor:"pointer",width:30,marginTop:5}} alt="" onClick={()=>this.stopQaByQaId(row,true)} />
                  }
                  {/*<Switch checked={row.disabled} checkedChildren="启用" unCheckedChildren="停用" onChange={(value) => this.stopQaByQaId(row,value)} />*/}
                </div>
            <img src={moreImg} alt="" className={styles.more} />
          </div>;
        },
        width: '250px',
      },
    ];
    this.uploadProps = {
      name: 'file',
      action: '/cloud/qa/importNew',
      accept:'.xlsx',
      onChange:  this.handleChangeByUpload,
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    this.fetchListBySearch();
  };

  handleMouseOut(){
    console.log('out')
  };

  handleMouseUserOver(e){
    console.log('in')
  };

  // 比较props变化判断是否是查看分类详情操作
  componentWillReceiveProps(nextProps, nextContext) {
    const { currentUser} = this.props;
    let isShard = false;
    if(nextProps.categoryId !== this.state.categoryId ){
        if(nextProps.categoryId.indexOf(currentUser.robotId) == -1){
          console.log('共享过来的知识点');
          isShard = true
        }
      this.setState({
        code:nextProps.code,
        categoryId: nextProps.categoryId,
        nodePath:nextProps.nodePath,
        categoryName: nextProps.categoryName,
        loading:true,
        page:1,
        isNoAnswer:nextProps.noAnswer,
        isShard
      },()=>{
        this.fetchListBySearch();
      })
    }
    if(nextProps.code !== this.state.code ){
      this.setState({
        code:nextProps.code,
      },()=>{
        this.fetchListBySearch();
      })
    }
  }

  getStr = (string,str,callback)=>{
    var str_before = string.split(str)[0];
    var str_after = string.split(str)[1];
    callback(str_before,str_after);
    console.log('前：'+str_before+' - 后：'+str_after);
  };

  // 搜索
  fetchListBySearch =(obj)=>{
    const { dispatch ,currentUser} = this.props;
    console.log(this.state);
    let object = {};
    if( obj){
      object = obj
    }
    this.setState({
      tableLoading: true
    },()=>{
      object.disabled = this.state.disabled;
      if(object.disabled ==='All'){
        delete object.disabled
      }
      object.qaType = this.state.qaType;
      if(object.qaType ==='All'){
        delete object.qaType
      }
      object.robotId = currentUser.robotId;
      object.limit = this.state.limit;
      object.page = this.state.page;
      object.query = this.state.key;
      object.categoryId = this.state.categoryId ==='' ? currentUser.robotId+'-root': this.state.categoryId ;
      object.queryType = object.queryType ===undefined ? this.state.queryType: object.queryType;
      object.isNoneAnswer =  this.state.isNoAnswer;
      object.sortType = this.state.sortType;
      dispatch({
        type: 'qaList/fetchListBySearch',
        payload: object,
        callback:(res)=>{
          this.setState({
            res: res.list,
            total:res.total,
            searchObj:object,
            loading:false,
            tableLoading: false,
            qaIdList:[],
            classId:'',
            selectedRowKeys:[]
          })
        }
      });
    });
  };

  handleChange=(value)=> {
    this.setState({
      sortType:value,
      loading:true,
    },()=>{
      this.fetchListBySearch()
    })
  };

  fetchQaListBySearch =(e)=>{
    if(e !== ''){
      e.preventDefault();
    }
    this.props.form.validateFields((err, values) => {
      const obj = values;
      if (!err) {
        this.setState({
          key: obj.key,
          page:1
        },()=>{
          this.fetchListBySearch(obj)
        })
      }
    });
  };

  stopQaByQaId=(row,type)=>{
    const { dispatch ,currentUser} = this.props;
    let arr = [];
    arr.push(row._id);
    dispatch({
      type: 'qaList/stopQaByQaId',
      payload: {robotId:currentUser.robotId,qaIdList:arr,disabled:type},
      callback: (res)=>{
        message.info('操作成功');
        this.setState({
          loading: true
        },()=>{
          this.fetchListBySearch();
        })
      }
    });

  };


  // 翻页
  fanye(e) {
    this.setState({
      page: e,
      loading:true,
      tableLoading: true,
      selectedRowKeys:[]
    }, () => {
      this.fetchListBySearch();
    });
  };


  // 导入弹出层
  handleOk = (e) => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file.originFileObj);
    });
    this.setState({
      uploading: true
    });
    this.uploadFile(formData);
  };


  handleQa=(e)=>{
    if(this.state.mergeId ===''){
      return message.error('请选择需要合并的问题')
    }
    this.combine();
  };

  handleQaCancel = (e) => {
    this.setState({
      mergeVisible: false,
      qaKey:''
    });
  };

  handleCancel = (e) => {
    this.setState({
      visible: false,
      mergeVisible: false,
      qaKey:'',
      fileList:[],
      uploading:false
    });
  };

  handleClass=(e)=>{
    this.updateQACategory()
  };

  updateQACategory=()=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'qaList/moveQaCategory',
      payload: {qaId:this.state.qaIdList,categoryPath:this.state.classId},
      callback: (res)=>{
       if(!res.code){
         this.setState({
           classVisible: false,

         });
         message.info('操作成功');
         this.fetchListBySearch();
       }
      }
    });
  };

  handleClassCancel = (e) => {
    this.setState({
      classVisible: false,
      qaIdList:[]
    });
  };

  handleClassShow=(e)=>{
    if(this.state.qaIdList.length===0){
      return  message.error('请选择需要移动分类的知识点')
    }
    this.getCategoryListJson();
    this.setState({
      classVisible: true,
    });
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };


  // 删除
  delQaByQaId=(row)=>{
    const { dispatch ,currentUser} = this.props;
    let arr = [];
    console.log(row)
    if(row){
      arr.push(row._id);
    }else{
      arr = this.state.qaIdList;
    }
    if(arr.length === 0){
      return message.info('请先选择需要删除的知识点')
    }
    const  that = this;
    confirm({
      title: '删除知识点',
      content: '是否确定删除这些知识点？',
      okText:"确认",
      cancelText:"取消",
      onOk() {
        dispatch({
          type: 'qaList/delListByQaId',
          payload: {qaIdList: arr,robotId: currentUser.robotId},
          callback:(res)=>{
            if(!res.code){
              message.info(res.msg);
              that.setState({
                qaIdList:[]
              },()=>{
                that.fetchListBySearch();
              });
            }
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  editQa = (row)=>{
    if(row){
      this.props.editQaById(row._id,this.state.nodePath,this.state.isShard);
    }else{
      this.props.editQaById('',this.state.nodePath,this.state.isShard);
    }
  };

  // 添加
  showDrawer = () => {
    this.setState({
      close: true,
    });
  };

  onClose = () => {
    this.setState({
      close: false,
    });
  };

  // 导出知识点
  exportQA =()=>{
    const {dispatch,currentUser} = this.props;
    let object = {};
    object.robotId = currentUser.robotId;
    object.query = this.state.key;
    object.categoryId = this.state.nodePath;
    object.sortType = this.state.sortType;
    object.categoryId = this.state.categoryId ==='' ? currentUser.robotId+'-root': this.state.categoryId ;
    object.queryType = object.queryType ===undefined ? this.state.queryType: object.queryType;
    object.isNoneAnswer = object.isNoneAnswer === undefined ? this.state.isNoAnswer: object.isNoAnswer;
    dispatch({
      type: 'qaList/exportQAById',
      payload: object,
      callback:(res)=>{
        let filename =decodeURIComponent( res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob,filename)
      }
    });

  };

  // 合并知识点
  mergeQaByQaId=()=>{
    console.log(this.state.qaIdList);
    if(this.state.qaIdList.length===0){
      return message.error('请先选择需要合并的知识点')
    }
    this.fetchListByModalSerach();
    this.setState({
      mergeVisible: true
    })
  };

  qaSearch=(val)=>{
    this.setState({
      qaKey: val,
      key:val,
      qaPage:1
    },()=>{
      this.fetchListByModalSerach()
    })
  };

  checkedQa=(e)=>{
    this.setState({
      mergeId : e.target.value._id
    })
  };

  fetchListByModalSerach =()=>{
    const { dispatch ,currentUser} = this.props;
    let object = {};
    object.robotId = currentUser.robotId;
    object.limit = this.state.qaLimit;
    object.page = this.state.qaPage;
    object.query = this.state.key;
    object.categoryId = '/' ;
    object.queryType = object.queryType ===undefined ? this.state.queryType: object.queryType;
    object.isNoneAnswer = object.isNoneAnswer === undefined ? false: object.isNoneAnswer;
    object.sortType = this.state.sortType;
    dispatch({
      type: 'qaList/fetchListBySearch',
      payload: object,
      callback:(res)=>{
        this.setState({
          qaRes: res.list,
          qaTotal:res.total,
          qaLoading: false
        })
      }
    });
  };

  qaFanye=(e)=>{
    this.setState({
      qaPage: e,
    },()=>{
      this.fetchListByModalSerach()
    })
  };

  combine=()=>{
    const { dispatch ,currentUser} = this.props;
    dispatch({
      type: 'qaList/combine',
      payload: {robotId:currentUser.robotId,from:this.state.qaIdList,to:this.state.mergeId},
      callback:(res)=>{
        message.info('合并成功');
        this.setState({
          mergeVisible: false,
          qaKey:'',
          key:""
        },()=>{
          this.fetchListBySearch()
        });
      }
    });
  };

  onClassChange=(value,label, extra)=>{
    this.setState({
      classId: value
    })
  };

  getCategoryListJson=()=>{
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'qaList/categoryListJson',
        payload: { },
        callback: (res) => {
          let arr = [];
          arr.push(res[0]);
          this.setState({
            classTreeData:arr
          },()=>{

            this.setState({
              classLoading: false
            })
          })
        }
      })
    });
  };

  renderTreeNodes(data) {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.text} key={item.id} path={item.path} value={item.data.path}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.text} key={item.id} value={item.data.path} path={item.path} />;
    });
  }

  pageSizeChange=(current,size)=>{
    this.setState({
      page: current,
      limit: size,
      tableLoading: true
    },()=>{
      this.fetchListBySearch();
    })
  };

  setNoAnswer=(val)=>{
    this.setState({
      isNoAnswer: !val
    })
  };

  setQaKey=(e)=>{
    this.setState({
      qaKey:e.target.value,
      key:e.target.value
    })
  };

  setClassName=(record)=>{
    return !record.enable ? styles.grey : ''
  };
  // fixTreeData=(arr)=> {
  //   let temp = [];
  //   let fn = function(arr) {
  //     for(let i of arr){
  //       if(i.children){
  //         fn(i.children)
  //       }
  //       i.value=i.id;
  //       i.title=i.text;
  //       i.key = i.id;
  //       temp.push(i)
  //     }
  //   };
  //   fn(arr);
  //   return temp
  // };
  handleChangeByUpload = info => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
       if(file.response.code){
         message.error(file.response.msg)
       }else{
         file.url = file.response.url;
       }
      }
      return file;
    });
    this.setState({ fileList });
  };


  setQuery=(e)=>{
    this.setState({
      key:e.target.value
    })
  };

  setStatus=(e)=>{
    this.setState({
        disabled:e
    })
  };

  setQueryType=(e)=>{
    this.setState({
      queryType:e
    })
  };

  setQaType=(e)=>{
    this.setState({
      qaType:e
    })
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys, qaIdList:selectedRowKeys })
  };

  handleUpFile=(info)=>{
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    this.setState({ fileList });
  };

  uploadFile=(data)=>{
    const robotId = (window.localStorage.getItem("robotId")) == undefined ? '' : (window.localStorage.getItem("robotId")) ;
    const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token ;
    axios.post('/cloud/new/knowledge/base/import', data, {
      method: 'post',
      processData: false,
      headers: {'Content-Type': 'multipart/form-data;charset=UTF-8',"token":token,'robotId':robotId}
    }).then((res) => {
      this.setState({
        uploading:false
      },()=>{
        // console.log(res.headers.date)
        this.props.qaListPd(res.headers.date)
        if(res.data.code){
          return message.error(res.data.msg)
        }else{
          this.setState({
            visible:false,
            fileList:[]
          },()=>{
            if(res.data.msg){
              message.success(res.data.msg);
            }else{
              message.success('导入成功');
            }
            this.fetchListBySearch()
          });

        }
      })

    }).catch((error) => {
     message.error('导入失败请稍等再试')
    });
  };

  downloadQaTemp=()=>{
    const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token ;
    const headData = {"Content-Type":"application/json","token":token};
    const params = qs.stringify({});
    const newUrl = '/cloud/new/knowledge/base/import/template'+"?"+params;
    fetch(newUrl,{headers:headData}).then(res=>res.blob().then(blob=>{
      let filename =decodeURIComponent( res.headers.get('Content-Disposition').split('=')[1]);
       download.byBlob(blob,filename)
      })
    )
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {items,total} = this.props.qaList;
    const { selectedRowKeys,uploading, fileList } = this.state;
    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept:'.xlsx',
      fileList,
      onChange: this.handleUpFile,
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 },
      },
    };
    return (
      <Suspense fallback={<PageLoading/>} >
        <div className="homecard">
        <Card bordered={false} className={styles.dabContent}>
          <Row gutter={16}>
            <h1 style={{ fontWeight: 600,marginBottom:10,color:'#4a90e2',fontSize:'16px' }}>{this.state.categoryName}({total})</h1>
          </Row>
          <div style={{marginBottom:20 }}>
            <div>
              <div style={{ display: 'inline-block',verticalAlign:'middle'}}>
                <Form layout="inline" onSubmit={this.fetchQaListBySearch}>
                  <Form.Item>
                    {getFieldDecorator('key', {
                      rules: [{
                        required: false,
                      }, {
                        validator: '',
                      }],
                      initialValue: '',
                    })(
                      <Input
                        placeholder="请输入知识点、词槽或接口名称的关键词"
                        style={{ width: 'calc(100vw - 1200px)',marginBottom:20}}  onChange={this.setQuery}
                        suffix={
                          <img src={searchImg} style={{cursor:"pointer",width:20}} alt="" onClick={()=>this.fetchQaListBySearch('')} />
                        }
                      />
                    )}
                  </Form.Item>
                </Form>
              </div>
              <div style={{ display: 'inline-block',verticalAlign:'middle'}}>

                    <div>
                      <img
                        onClick={()=>this.editQa()}
                        style={{ cursor: 'pointer',marginRight:-5 }}
                        src={addImg}
                      />
                      <img
                        onClick={()=>this.showModal()}
                        style={{ cursor: 'pointer',marginRight:-5}}
                        src={importImg}
                      />
                      <img
                        onClick={()=>this.exportQA()}
                        style={{ cursor: 'pointer',marginRight:-5}}
                        src={exportImg}
                      />
                      <img
                        onClick={()=>this.delQaByQaId()}
                        style={{ cursor: 'pointer',marginRight:-5}}
                        src={delImg}
                      />
                      <img
                        onClick={()=>this.mergeQaByQaId()}
                        style={{ cursor: 'pointer',marginRight:-5}}
                        src={mergeImg}
                      />
                      <img
                        onClick={()=>this.handleClassShow()}
                        style={{ cursor: 'pointer',marginRight:-5}}
                        src={moveImg}
                      />
                      {/*<Button htmlType='button' type="primary" style={{ margin: 5 }}*/}
                      {/*        onClick={() => this.showModal()}><FormattedMessage id="app.overView.lead"/></Button>*/}
                      {/*<Button htmlType='button' type="primary" style={{ margin: 5 }}*/}
                      {/*        onClick={() => this.exportQA()}><FormattedMessage id="app.overView.export"/></Button>*/}
                      {/*<Button htmlType='button' type="primary" style={{ margin: 5 }}*/}
                      {/*        onClick={() => this.delQaByQaId()}><FormattedMessage id="app.overView.del"/></Button>*/}
                      {/*<Button htmlType='button' type="primary" style={{ margin: 5 }}*/}
                      {/*        onClick={() => this.mergeQaByQaId()}><FormattedMessage id="app.overView.merge"/></Button>*/}
                      {/*<Button htmlType='button' type="primary" style={{ margin: 5 }}*/}
                      {/*        onClick={() => this.handleClassShow()}><FormattedMessage id="app.overView.remove"/></Button>*/}
                    </div>
              </div>
            </div>
            <div>
              <Form layout="inline"  onSubmit={this.fetchQaListBySearch}>
                <Form.Item>
                  {getFieldDecorator('queryType', {
                    rules: [{
                      required: false,
                    }, {
                      validator: '',
                    }],
                    initialValue: 'question',
                  })(
                    <Select style={{ width: 189 }} onChange={this.setQueryType}>
                      <Option value="question">搜索问题</Option>
                      <Option value="answer">搜索答案</Option>
                      <Option value="slot">搜索词槽名称</Option>
                      <Option value="api">搜索接口名称</Option>
                    </Select>,
                  )}

                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('disabled', {
                    rules: [{
                      required: false,
                    }, {
                      validator: '',
                    }],
                    initialValue: 'All',
                  })(
                    <Select style={{ width: 189 }} onChange={this.setStatus}>
                      <Option value="All">所有状态</Option>
                      <Option value="false">启用</Option>
                      <Option value="true">停用</Option>
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('qaType', {
                    rules: [{
                      required: false,
                    }, {
                      validator: '',
                    }],
                    initialValue: 'All',
                  })(
                    <Select style={{ width: 189 }} onChange={this.setQaType}>
                      <Option value="common">普通知识点</Option>
                      <Option value="slot">词槽知识点</Option>
                      <Option value="induce">流程引导知识点</Option>
                      <Option value="All">所有类型</Option>
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('isNoneAnswer', {
                    initialValue: '',
                  })(
                    <span>
                 {
                   this.state.isNoAnswer?
                     <img src={onImg} style={{cursor:"pointer",width:30}} alt="" onClick={()=>this.setNoAnswer(this.state.isNoAnswer)} />
                     :
                     <img src={offImg} style={{cursor:"pointer",width:30}} alt="" onClick={()=>this.setNoAnswer(this.state.isNoAnswer)}/>
                 }
                      <span>无答案</span></span>
                  )}
                </Form.Item>
              </Form>
            </div>
          {/*<div style={{ float: 'right' }}>*/}
          {/*  <Select defaultValue={this.state.sortType} onChange={this.handleChange} style={{ margin: 10, width: 150 }}>*/}
          {/*    <Option value="updateTime"><FormattedMessage id="app.overView.updateTime"/></Option>*/}
          {/*    <Option value="addTime"><FormattedMessage id="app.overView.addTime"/></Option>*/}
          {/*    <Option value="questionCount">相似问少</Option>*/}
          {/*  </Select>*/}
          {/*</div>*/}
        </div>
        <Table
          rowSelection={rowSelection}
          className="zdyTable"
          rowClassName={this.setClassName}
          columns={this.columns}
          dataSource={this.state.res}
          rowKey="_id"
          pagination={false}
          loading={this.state.tableLoading}
        />
        <Pagination
          style={{ textAlign: 'center', marginTop: 30, marginBottom: 20 }}
          showSizeChanger
          total={parseInt(this.state.total)}
          current={this.state.page}
          onChange={e => this.fanye(e)}
          onShowSizeChange={(current, size) => this.pageSizeChange(current, size)}
          showTotal={() => `共 ${this.state.total} 条`}
        />
        </Card>
        </div>
        <Modal
          title={<FormattedMessage id="app.overView.leadQa"/>}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          width='630px'
          centered
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
            <Button key="submit" type="primary" loading={uploading}  disabled={fileList.length === 0} onClick={this.handleOk}>
              {uploading ? '导入中' : '开始导入'}
            </Button>,
          ]}
        >
          <Form {...formItemLayout}>
            <Form.Item label={<FormattedMessage id="app.overView.file"/>}>
              <Upload {...props}>
                <Button>
                  <Icon type="upload" /> <FormattedMessage id="app.overView.file"/>
                </Button>
              </Upload>
            </Form.Item>
            <Form.Item label={<FormattedMessage id="app.overView.file"/>}>
              <div style={{ border: '1px solid grey', padding: 10, borderRadius: 10, overflow: 'hidden' }}>
                <div>•请按照模板中的示例格式进行编辑上传：<span style={{color:'blue',cursor:'pointer'}} onClick={()=>this.downloadQaTemp()}>下载知识点导入模板</span></div>
                <div>•上传文件格式需要为“.xlsx”类型的Excel文件</div>
                <div>•第一列的知识点ID如果有填写，则将对该ID知识点进行更新操作，如果没有填写，则将自动新增该知识点</div>
              </div>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title='合并到知识点'
          visible={this.state.mergeVisible}
          onOk={this.handleQa}
          onCancel={this.handleQaCancel}
          okText='合并'
          cancelText='取消'
          width='464px'
          centered
        >
          <Spin tip="Loading..." spinning={this.state.qaLoading}>
            <div style={{ overflow: 'hidden' }}>
              <p>选择要合并到的知识点</p>
              <div style={{ padding: 10 }}>
                <div>
                  <Search
                    placeholder='请输入关键字搜索问题'
                    onSearch={value => this.qaSearch(value)}
                    value={this.state.qaKey}
                    onChange={e => this.setQaKey(e)}
                    style={{ width: 300 }}
                  />
                </div>
                <div>
                  <RadioGroup onChange={this.checkedQa}>
                    {
                      this.state.qaRes.map((qa, index) => {
                        return (
                          <div key={index} style={{ marginTop: 10 }}>
                            <Radio value={qa}><span style={{
                              marginLeft: 10,
                              display: 'inline-block',
                              maxWidth: 318,
                              whiteSpace: 'initial',
                            }}>{qa.stdQuestion}</span></Radio>
                          </div>
                        );
                      })
                    }
                  </RadioGroup>
                </div>
              </div>
              <p style={{ color: 'grey', fontSize: 12, marginTop: 10 }}>合并后，原知识点将添加到该知识点，同时原知识点将被删除</p>
              <Pagination
                size='small'
                total={parseInt(total)}
                onChange={e => this.qaFanye(e)}
                style={{ float: 'right', marginTop: '10px' }}
              />
            </div>
          </Spin>
        </Modal>
        <Modal
          title='移动分类'
          visible={this.state.classVisible}
          onOk={this.handleClass}
          onCancel={this.handleClassCancel}
          okText='确定'
          cancelText='取消'
          width='464px'
          centered
        >
          <Spin tip="Loading..." spinning={this.state.classLoading}>
            <div style={{ overflow: 'hidden' }}>
              <Form {...formItemLayout}>
                <Form.Item label="移动到分类">
                  <TreeSelect
                    style={{ width: 300, marginLeft: 10 }}
                    allowClear
                    showSearch
                    placeholder="请选择分类"
                    treeNodeFilterProp='title'
                    value={this.state.classId}
                    treeDefaultExpandedKeys={['root']}
                    showCheckedStrategy='SHOW_PARENT'
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    onChange={(value, label, extra) => this.onClassChange(value, label, extra)}
                  >
                    {this.renderTreeNodes(this.state.classTreeData)}
                  </TreeSelect>
                </Form.Item>
              </Form>
            </div>
          </Spin>
        </Modal>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(QaList));
